#include "aky_com_include.h"

static volatile uint32_t delay_tick = 0;

static volatile uint32_t time_tick = 0;
static volatile uint32_t g_target_tick = 0;
static volatile uint8_t g_time_stat = 0;
static volatile uint32_t g_off_time_tick = 0;

void aky_delay_init(void)
{
    delay_tick = 0;
    time_tick = 0;
}


//tick心跳
void aky_delay_tick_incre_pro(void)
{
    delay_tick++;
    time_tick++;
    g_off_time_tick++;
    if (time_tick % (g_target_tick / AKY_TICK_INTERVAL) == 0)
    {
        if (g_time_stat == 1)
        {
            g_time_stat = 0;
        }
        else
        {
            g_time_stat = 1;
        }
    }
}

static void aky_delay_tick_clr(void)
{
    delay_tick = 1;
}

static uint32_t aky_get_cur_tick(void)
{
    return delay_tick;
}


//根据tick进行延时,
void aky_tick_delay_ms(uint32_t ms)
{
    uint32_t target_tick = 0;
    if (ms <= AKY_TICK_INTERVAL)
    {
        target_tick = 1;   
    }  
    else
    { 
        target_tick = ms / AKY_TICK_INTERVAL;
    }
    aky_delay_tick_clr();
    while (1)
    {
        if (aky_get_cur_tick() > target_tick) 
        {
            break;
        }     
    } 
}


//软件延时,较不准确
void aky_soft_delay_ms(uint32_t ms)
{
    volatile uint32_t cur_sys_clc = 0;
    uint32_t delay_cnt = 0;
    cur_sys_clc = 20000000;
    while (ms)
    {
        ms--;
        delay_cnt = cur_sys_clc / (100000ul);
        while (delay_cnt)
        {
            delay_cnt--;
        }
    }
}


//设置翻转的目标时间
void set_target_time(uint32_t target_tick)
{
    g_target_tick = target_tick;
}


//根据设定的目标时间周期置零置一
//target_tick 目标时间
//return 翻转状态
uint8_t aky_get_target_time_stat(uint32_t target_tick)
{
    set_target_time(target_tick);
    return g_time_stat;
}


void off_time_tick_clr(void)
{
    g_off_time_tick = 0;
}

//获取当前自动关机时间tick
uint32_t get_cur_off_time_tick(void)
{
    return g_off_time_tick;
}


//判断是否到达关机时间
//target_off_time 目标关机时间 单位为秒 如传参为10则到达10s后返回1
//return \1到达关机时间
uint8_t aky_off_time_trig(uint16_t target_off_time)
{
    uint8_t res = 0;
    uint32_t temp_u32 = 0;
    temp_u32 = target_off_time * (1000ul);
    if (get_cur_off_time_tick() > (temp_u32 / AKY_TICK_INTERVAL))
    {
        res = 1;
    }
    return res;
}

//预留
void delay(uint32_t delay)
{
    aky_tick_delay_ms(delay * (10ul));
}
